/*
 * @Author: yangzonglong
 * @Date: 2020-09-23 09:55:48
 * @version: v1.0.0
 * @Descripttion: 通用导出xlsx文件
 * @LastEditors: yangzonglong
 * @LastEditTime: 2020-09-23 17:45:10
 * @Auditor: 
 */
import * as XLSX from 'xlsx/xlsx.mjs';
import { ColumnProps } from './../../components/table/interface';

interface Options {
  columns: ColumnProps<any>[];
  dataSource: any[];
  fileName?: string
}

export default ({ columns, dataSource, fileName }: Options) => {
  const excelArr: Record<string, any>[] = [];

  const fiedsData = columns.reduce((next, cur) => {
    next[cur.dataIndex as string] = cur.title || window.$app.t(cur.dataIndex as string);
    return next
  }, {});

  [fiedsData, ...dataSource].forEach((item, index) => {
    excelArr[index] = {};
    columns.forEach(column => {
      excelArr[index][column.dataIndex as string] = item[column.dataIndex as string];
    })
  })
  createXlsx(excelArr, columns, fileName)
}

function createXlsx(excelArr: Record<string, any>[], columns: ColumnProps<any>[], fileName?: string) {
  const defaultFileName = +(new Date()) + '.xlsx';
  const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(excelArr);
  const wsOptions = columns.map(item => ({ width: (item.width as number) || 20 }));
  ws['!cols'] = wsOptions;
  const wb: XLSX.WorkBook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, fileName || defaultFileName);
}